#!/usr/bin/env node

const readline = require('readline');
const { validateProbabilities, calculateEntropy } = require('./entropyUtils');

// 解析命令行参数
const args = process.argv.slice(2);
let probabilities = [];

// 如果没有命令行参数，进入交互模式
if (args.length === 0) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: '请输入概率值（0到1之间的数），按Ctrl+D结束输入： '
  });

  let probabilityCount = 0; // 用于跟踪输入的概率值数量

  const askForProbability = () => {
    if (probabilityCount >= 2) {
      console.log('已输入两个概率值，按Ctrl+D结束输入。');
      rl.close();
      return;
    }
    rl.question(`p${probabilityCount}：`, input => {
      const num = parseFloat(input.trim());
      if (isNaN(num) || num < 0 || num >= 1) {
        console.error('输入无效，请输入0到1之间的数。');
        askForProbability();
      } else {
        probabilities.push(num);
        probabilityCount++;
        if (probabilityCount < 2) {
          askForProbability(); // 继续询问直到至少有两个概率值
        } else {
          // 检查概率和是否为1
          if (!validateProbabilities(probabilities)) {
            console.error('概率空间不封闭，概率和需等于1！');
            process.exit(1);
          }
          process.exit(0);
        }
      }
    });
  };

  askForProbability();
} else {
  try {
    probabilities = args.map(arg => {
      const num = parseFloat(arg);
      if (isNaN(num) || num < 0 || num >= 1) {
        throw new Error(`"${arg}" 不是一个有效的数字或不在0到1的范围内。`);
      }
      return num;
    });
    // 检查概率和是否为1
    if (!validateProbabilities(probabilities)) {
      throw new Error('概率空间不封闭，概率和需等于1！');
    }
    console.log(`p=[${probabilities.join(',')}]`);
    console.log(`h(p) = ${calculateEntropy(probabilities).toFixed(3)} bit`);
  } catch (error) {
    console.error(error.message);
    process.exit(1);
  }
}